/*
 * Copyright (C) 2012 CNL - ECE Dept - National University of Singapore
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package sg.nus.ece.cnl.veracity;

import java.io.File;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import sg.nus.ece.cnl.veracity.access.SshUserCredentials;
import sg.nus.ece.cnl.veracity.access.TargetServer;
import sg.nus.ece.cnl.veracity.configuration.VeracityConfiguration;
import sg.nus.ece.cnl.veracity.configuration.VeracityDefaultValues;
import sg.nus.ece.cnl.veracity.hadoop.ClusterDeployer;
import sg.nus.ece.cnl.veracity.hadoop.ClusterStarter;

/**
 * This class provides several APIs allowing user to manage the virtual machines
 * including creation (deployment) of new VMs, migration of one VM to the other,
 * rebooting or shutdown VMs. It uses the XEN APIs provided by Citrix Community.
 *
 * @author tram
 */
public class Main {

    private static final Logger log = Logger.getLogger(Main.class);

    /**
     * Prints Main command line usage and exit with given return code.
     *
     * @param code return code
     * @param error error message to display
     */
    public static void usage(int code, String error) {
        log.info("Usage: java Veracity [--config|-c configuration_file] <number_of_vm_instances> ");
        log.info("       java Moteur2 <--help|-h>");
        System.out.println();
        log.info("       --config|-c <configuration_file>");
        log.info("       path of configuration file, default is \"~/.veracityrc\"");
        log.info("       <number_of_vm_instances>");
        log.info("       number of vm instances to be deployed for the Hadoop Cluster");
        if (error != null) {
            System.err.println();
            log.error(error);
        }
        System.exit(code);
    }

    /**
     * Main entry point. Read command line and start the deployment.
     *
     * @param args command line
     */
    public static void main(String[] args) {

        int vmInstances = 0;
        String vmTemplate = "";
        
        // init log4j properties
        PropertyConfigurator.configure(Main.class.getClassLoader().getResource("veracityLog4j.properties"));


        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("--config") || args[i].equals("-c")) {
                if (++i >= args.length) {
                    usage(-1, "No argument found to " + args[i - 1] + " option");
                }
                VeracityConfiguration.initConfiguration(new File(args[i]));
            } else if (args[i].equals("--template") || args[i].equals("-t")) {
                if (++i >= args.length) {
                    usage(-1, "No argument found to " + args[i - 1] + " option");
                }
                vmTemplate = args[i];
            } else if (args[i].charAt(0) != '-') {
                try {
                    vmInstances = Integer.parseInt(args[i]);
                } catch (NumberFormatException ex) {
                    usage(-1, "Invalid number of vm instances: " + ex.getMessage());
                }
            }
        }
      
        // depploy Hadoop cluster and start hadoop deamons
        if (vmInstances != 0 && vmTemplate != null && !vmTemplate.isEmpty()) {

            TargetServer targetServer = new TargetServer(VeracityDefaultValues.getDefaultXenServerHostname());
            SshUserCredentials userCredentials = new SshUserCredentials(VeracityDefaultValues.getDefaultXenServerUserLogin(),
                    VeracityDefaultValues.getDefaultXenServerUserPassword());

            try {
                Map<String, String> vmInstancesMap = ClusterDeployer.getInstance().deployHadoopCluster(targetServer, userCredentials, vmTemplate, vmInstances);
                if (vmInstancesMap != null) {
                    ClusterStarter.getInstance().startCluster(targetServer, userCredentials, vmInstancesMap);
                }
            } catch (sg.nus.ece.cnl.veracity.exception.VeracityException ex) {
                log.error("Cannot deploy and start Hadoop Cluster: " + ex.getMessage());
                System.exit(-1);
            }
        }
    }
}
